package neichuan.message;

import io.netty.buffer.ByteBuf;

import java.util.HashMap;
import java.util.Map;

public class Message {
    int bytesLength=-1;

    private int type=-1;
    private int content_length=-1;
    private Map<Integer,byte[]> headers;
    private byte[] data;

    public Message(int type,Map headers,byte[] data){
        this.type=type;
        this.headers=headers;
        setData(data);
    }

    public Message(MessageType type, Map headers, byte[] data){
        this.type=type.getType();
        this.headers=headers;
        setData(data);
    }

    public int getBytes(ByteBuf byteBuf){
//        if(bytesLength<=0){
        bytesLength=0;
        bytesLength+=3*4;//一个type,一个content_length,一个headers.size
        if(headers!=null){
            headers.values().forEach(h->{bytesLength+=h.length;});//headers.value
            bytesLength+=(headers.size()*2)*4;//headers.size*2
        }
        bytesLength+=content_length;//data
//        }
        byteBuf.writeInt(bytesLength);
        byteBuf.writeInt(type);
        byteBuf.writeInt(content_length);
        if(headers!=null){
            byteBuf.writeInt(headers.size());
            headers.forEach((k,v)->{byteBuf.writeInt(v.length).writeInt(k).writeBytes(v);});
        }
        else {
            byteBuf.writeInt(0);
        }
        if(data!=null){
            byteBuf.writeBytes(data);
        }
        return bytesLength;
    }

    public void setData(byte[] data){
        this.data=data;
        this.content_length=0;
        if(data!=null){
            this.content_length=data.length;
        }
    }

    public void setHeader(Integer key,byte[] value) {
        headers.put(key,value);
    }

    public void setHeader(MessageHeaderFiled key, byte[] value) {
        headers.put(key.getFiled(),value);
    }

    public void setHeader(MessageHeaderFiled key, String value) {
        if(headers==null){
            headers=new HashMap<>();
        }
        headers.put(key.getFiled(),value.getBytes());
    }

    public void setType(int type){
        this.type=type;
    }

    public int getType(){
        return type;
    }

    public byte[] getData() {
        return data;
    }

    public Map<Integer, byte[]> getHeaders() {
        return headers;
    }

    public String getHeader(int key){
        if(headers==null){
            return null;
        }
        return new String(headers.get(key));
    }

    public int getContent_length(){
        return content_length;
    }

}
